package com.quanyan.club.service.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.response.RespUserAccumulateModify;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.resp.task.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.mq.constant.MqConstant;
import com.quanyan.club.mq.producer.BatchGiveOutEggsProducer;
import com.quanyan.club.service.ClubIntegralService;
import com.quanyan.club.service.ClubTaskEggService;
import com.quanyan.club.service.CppService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.utils.VersionUtils;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.joda.time.DateTime;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/11/14.
 *
 * 俱乐部鸟蛋任务服务实现类
 */
@Service
public class ClubTaskEggServiceImpl extends BaseServiceImpl implements ClubTaskEggService {

    private Logger logger = LoggerFactory.getLogger(ClubTaskEggServiceImpl.class);

    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbClubTaskClubEggStreamMapper clubTaskClubEggStreamMapper;
    @Autowired
    private TbClubTaskMemEggStreamMapper clubTaskMemEggStreamMapper;
    @Autowired
    private TbClubTaskMapper clubTaskMapper;
    @Autowired
    private TbClubTaskClubTypeMapper clubTaskClubTypeMapper;
    @Autowired
    private TbClubTaskParameterMapper clubTaskParameterMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private BatchGiveOutEggsProducer batchGiveOutEggsProducer;
    @Autowired
    private UserAssetsService userAssetsService;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ClubEggTaskMapper clubEggTaskMapper;
    @Autowired
    private PlaceClient placeClient;
    @Autowired
    private TbClubTaskSummaryLogMapper clubTaskSummaryLogMapper;
    @Autowired
    private CppService cppService;
    @Autowired
    ClubIntegralService clubIntegralService;
    @Autowired
    private TbActivityMapper activityMapper;
    @Autowired
    private TbSystemParametersMapper systemParametersMapper;

    /**
     * 查询当前时间的自然周内，有活动结算的俱乐部完成鸟蛋任务情况
     */
    @Override
    public List<EggTaskFinishCase> queryFinishEggTaskClubs(){

        List<EggTaskFinishCase> finishCases = new ArrayList<>();

        Date currentDate = new Date();
        Date thisWeekMonday = DateUtils.getMondayOfWeek(currentDate, 0);
        Date thisWeekSunday = DateUtils.getSundayOfWeek(currentDate, 0);

        List<Integer> settleClubIds = clubEggTaskMapper.selectSettleClubs(DateUtils.dayBegin(thisWeekMonday), DateUtils.dayEnd(thisWeekSunday));
        List<Integer> clubTypes = Arrays.asList(1, 2, 3, 4);        //只要足篮网羽
        for (Integer clubId : settleClubIds){
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
            if (tbClub == null || tbClub.getIsDelete() == 1 || !clubTypes.contains(tbClub.getClubType())){
                continue;
            }
            try {
                EggTaskFinishCase eggTaskFinishCase = getWeekTask(clubId, tbClub.getClubType(), thisWeekMonday, thisWeekSunday, 0);
                if (eggTaskFinishCase != null) {
                    eggTaskFinishCase.setUid(tbClub.getUid());
                    eggTaskFinishCase.setClubName(tbClub.getClubName());
                    logger.warn("统计返回：-----" + JSON.toJSONString(eggTaskFinishCase));
                    finishCases.add(eggTaskFinishCase);
                }
            } catch (Exception e){
                logger.warn("queryFinishEggTaskClubs：" + e.getMessage());
            }
        }

        return finishCases;
    }

    /**
     * 直接更新一周内有结算的俱乐部周任务积分
     * @param startTime     周一零点
     * @param endTime       周日23:59:59
     */
    @Override
    public void directModifyClubWeekTaskStar(Date startTime, Date endTime){
        List<Integer> settleClubIds = clubEggTaskMapper.selectSettleClubs(DateUtils.dayBegin(startTime), DateUtils.dayEnd(endTime));
        List<Integer> clubTypes = Arrays.asList(1, 2, 3, 4);        //只要足篮网羽
        for (Integer clubId : settleClubIds){
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
            if (tbClub == null || tbClub.getIsDelete() == 1 || !clubTypes.contains(tbClub.getClubType())){
                continue;
            }
            try {
                EggTaskFinishCase taskFinishCase = getWeekTask(clubId, tbClub.getClubType(), startTime, endTime, 0);
                if (taskFinishCase != null) {
                    taskFinishCase.setUid(tbClub.getUid());
                    taskFinishCase.setClubName(tbClub.getClubName());
                    logger.warn("统计返回：-----" + JSON.toJSONString(taskFinishCase));

                    clubIntegralService.modifyClubWeekTaskStar(taskFinishCase.getClubId(),
                            taskFinishCase.getWeekActivityFinishCount(), taskFinishCase.getWeekActivityTargetCount(),
                            taskFinishCase.getWeekSignupFinishCount(), taskFinishCase.getWeekSignupTargetCount());
                }
            } catch (Exception e){
                logger.warn("queryFinishEggTaskClubs：" + e.getMessage());
            }
        }
    }

    private Date getSplitTime(){
        TbSystemParametersExample example = new TbSystemParametersExample();
        example.createCriteria().andParamKeyEqualTo("task.newuser.split.time").andIsEnableEqualTo(1);

        List<TbSystemParameters> parameterses = systemParametersMapper.selectByExample(example);
        if (parameterses == null || parameterses.size() == 0){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(parameterses.get(0).getParamValue());
        } catch (ParseException e) {

        }
        return null;
    }

    private boolean haveSettlementActivity(int clubId){

        TbClubActivitySettlementExample settlementExample = new TbClubActivitySettlementExample();
        settlementExample.createCriteria().andClubIdEqualTo(clubId);
        int count = clubActivitySettlementMapper.countByExample(settlementExample);
        if (count > 0){
            return true;       //一笔以上结算
        }
        return false;
    }

    /**
     * 获取鸟蛋任务列表
     * @param clubType  俱乐部类型
     * @param clubId    俱乐部id
     * @return
     */
    @Override
    public List<EggTaskFinishCase> getEggTaskFinishCaseList(int clubType, int clubId, String ver) {

        List<EggTaskFinishCase> weekTasks = new ArrayList<>();

        //0. 首次活动次任务
        List<Integer> taskIds = clubEggTaskMapper.getClubTaskId(2, clubType);
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        boolean isNewClub = false;
        boolean isNewUser = false;
        if (tbClub != null && tbClub.getIsDelete() != Constants.IS_DELETE_TRUE){
            Date splitDate = getSplitTime();
            if (splitDate != null) {
                TbClubExample example = new TbClubExample();
                example.createCriteria().andUidEqualTo(tbClub.getUid()).andClubTypeLessThanOrEqualTo(4);
                example.setOrderByClause(" create_time");
                List<TbClub> clubList = clubMapper.selectByExample(example);
                if (clubList != null && clubList.size() != 0){
                    isNewClub = (tbClub.getCreateTime().after(splitDate)) && (clubList.get(0).getId()==clubId);
                }
            }
            RespUserInfoBase userInfo = getUserInfoBase(tbClub.getUid());
            if (userInfo != null && splitDate != null){
                isNewUser = userInfo.getRegTime().after(splitDate);
            }
        }
        if (taskIds != null && taskIds.size() != 0 && isNewClub && isNewUser && !haveSettlementActivity(clubId)) {
            int taskId = taskIds.get(0);
            TbClubTaskSummaryLogExample example = new TbClubTaskSummaryLogExample();
            example.createCriteria().andTaskIdEqualTo(taskId).andClubIdEqualTo(clubId).andClubGetEggsNotEqualTo(0);
            if (clubTaskSummaryLogMapper.countByExample(example) == 0){
                //没有做首次活动奖励任务
                TbClubTask clubTask = clubTaskMapper.selectByPrimaryKey(taskId);
                if (clubTask != null && clubTask.getStatus() == 1){
                    Integer compareVer = VersionUtils.compareVersion(ver, "2.9");
                    if(null != ver && null != compareVer && compareVer >= 0) {
                        EggTaskFinishCase newCase = new EggTaskFinishCase();
                        newCase.setCanbeget(false);
                        newCase.setTaskType(2);  //新手任务
                        newCase.setClubId(clubId);
                        newCase.setTaskName(clubTask.getTaskName());
                        TbClubTaskParameterExample pExample = new TbClubTaskParameterExample();
                        pExample.createCriteria().andTaskIdEqualTo(taskId).andClubTypeEqualTo(clubId);
                        newCase.setTaskLevels(clubTaskParameterMapper.selectByExample(pExample));
                        Integer pid = getClubTaskParameter(clubType, clubTask.getId(), 0, 0);
                        if (pid != null) {
                            newCase.setRule(getTaskRule(pid));
                        }
                        newCase.setRuleDesc(clubTask.getRuleDescLink());
                        weekTasks.add(newCase);
                    }
                }
            }
        }

        //周任务
        TbClubTask clubTask = getClubTask(clubType);
        Date now = new Date();
        if (clubTask == null || clubTask.getStatus() != 1){
            throw new BizException("当前类型的俱乐部没有奖励任务");
        }
        if (clubTask.getActiveTimeStart() != null && clubTask.getActiveTimeEnd() != null        //任务有效时间
                && !(now.after(clubTask.getActiveTimeStart()) && now.before(clubTask.getActiveTimeEnd()))){
            throw new BizException("俱乐部奖励活动已经过期");
        }

        //1. 本周任务
        Date currentDate = new Date();
        Date thisWeekMonday = DateUtils.getMondayOfWeek(currentDate, 0);
        Date thisWeekSunday = DateUtils.getSundayOfWeek(currentDate, 0);
        EggTaskFinishCase thisWeekCase = getWeekTask(clubId, clubType, thisWeekMonday, thisWeekSunday, 0);
        if (thisWeekCase != null) {
            thisWeekCase.setTaskLevels(queryTaskParametersList(clubTask.getId(), clubType, "asc"));
            thisWeekCase.setTaskType(1);
            weekTasks.add(thisWeekCase);
        }

        //2. 上周任务
        Date lastWeekMonday = DateUtils.getMondayOfWeek(currentDate, -1);
        Date lastWeekSunday = DateUtils.getSundayOfWeek(currentDate, -1);
        logger.warn("lastWeekMonday" + lastWeekMonday + ", lastWeekSunday=" + lastWeekSunday);
        TbClub tbClub2 = clubMapper.selectByPrimaryKey(clubId);
        logger.warn("---------" + tbClub2.getCreateTime());
        if (tbClub2.getCreateTime().before(DateUtils.dayEnd(lastWeekSunday))) {
            EggTaskFinishCase lastWeekCase = getWeekTask(clubId, clubType, lastWeekMonday, lastWeekSunday, -1);
            if (lastWeekCase != null) {
                lastWeekCase.setTaskLevels(queryTaskParametersList(clubTask.getId(), clubType, "asc"));
                lastWeekCase.setTaskType(1);    //周任务
                weekTasks.add(lastWeekCase);
            }
        }

        return weekTasks;
    }

    /**
     * 获取任务 等级参数列表
     * @param taskId    任务id
     * @param sort      排序规则 desc asc
     */
    private List<TbClubTaskParameter> queryTaskParametersList(int taskId, int clubType, String sort){
        TbClubTaskParameterExample clubTaskParameterExample = new TbClubTaskParameterExample();
        clubTaskParameterExample.createCriteria()
                .andTaskIdEqualTo(taskId)
                .andClubTypeEqualTo(clubType);
        clubTaskParameterExample.setOrderByClause(" activity_target_count + signup_target_count " + sort); //排序
        List<TbClubTaskParameter> parametersList = clubTaskParameterMapper.selectByExample(clubTaskParameterExample);
        if (parametersList == null || parametersList.size() == 0){
            throw new BizException("任务奖励活动还未开始！");
        }
        return parametersList;
    }

    /**
     * 获取俱乐部的周任务
     */
    private TbClubTask getClubTask(int clubType){
//        TbClubTaskClubTypeExample taskClubTypeExample = new TbClubTaskClubTypeExample();
//        taskClubTypeExample.createCriteria()
//                .andClubTypeEqualTo(clubType);
//        List<TbClubTaskClubType> tbClubTaskClubTypes = clubTaskClubTypeMapper.selectByExample(taskClubTypeExample);
//        if (tbClubTaskClubTypes == null || tbClubTaskClubTypes.size() == 0){
//            return  null;
//        }
//
//        TbClubTask clubTask = clubTaskMapper.selectByPrimaryKey(tbClubTaskClubTypes.get(0).getTaskId());
        List<Integer> taskIds = clubEggTaskMapper.getClubTaskId(1, clubType);
        if (taskIds == null || taskIds.size() == 0){
            return null;
        }
        TbClubTask clubTask = clubTaskMapper.selectByPrimaryKey(taskIds.get(0));
        if(clubTask != null && clubTask.getStatus() == 1){
            return clubTask;
        }
        return null;
    }

    private BigDecimal getActivityMinPrice(int clubType, int taskId){
        TbClubTaskParameterExample example = new TbClubTaskParameterExample();
        example.createCriteria()
                .andClubTypeEqualTo(clubType).andTaskIdEqualTo(taskId);
        List<TbClubTaskParameter> parameters = clubTaskParameterMapper.selectByExample(example);
        if (parameters == null || parameters.size() == 0){
            return new BigDecimal(1);
        }
        return parameters.get(0).getActivityMinPrice();
    }

    /**
     * 获取周任务完成情况
     * @param clubId        俱乐部id
     * @param clubType      俱乐部类型
     * @param weekMonday    周一0点
     * @param weekSunday    周日23:59:59
     * @param week          周次 0 本周 -1 上周
     * @return
     */
    private EggTaskFinishCase getWeekTask(int clubId, int clubType, Date weekMonday, Date weekSunday, int week){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.warn("------------weekMonday=" + sf.format(weekMonday) + ", weekSunday=" + sf.format(weekSunday));
        List<Integer> thisWeekFinishActivitys = getWeekFinishActivityList(clubId,
                weekMonday, weekSunday);  //周发布的活动
        int weekFinishActivityCount = thisWeekFinishActivitys.size();

        TbClubTask clubTask = getClubTask(clubType);
        if (clubTask == null || clubTask.getStatus() != 1){
            logger.warn("{}类型俱乐部任务，不存在或状态!=1", clubType);
            return null;
        }

        BigDecimal minPrice = getActivityMinPrice(clubType, clubTask.getId());

        List<ActivitySignUpInfo> thisWeekFishSignups = getWeekFinishSignupList(clubId, minPrice,  //订单金额大于=1元的才算数
                thisWeekFinishActivitys);  //周报名的人数
        int weekFinishSignupCount = thisWeekFishSignups.size();

        logger.warn("------------weekFinishActivityCount=" + weekFinishActivityCount + ", thisWeekFishSignups=" + thisWeekFishSignups.size());

        Date now = new Date();
        if (clubTask.getActiveTimeStart() != null && clubTask.getActiveTimeEnd() != null        //任务有效时间
                && !(now.after(clubTask.getActiveTimeStart()) && now.before(clubTask.getMultipleEndTime()))){
            logger.warn("俱乐部任务{}已经过期", JSON.toJSON(clubTask));
            return null;
        }

        int taskId = clubTask.getId();
        List<TbClubTaskParameter> parametersList = queryTaskParametersList(taskId, clubType, "desc");
        TbClubTaskParameter maxLevel = parametersList.get(0);

        //筛选出离当前完成情况最近的任务奖励参数
        if (parametersList.size() > 1) {
            if (week == 0){
                parametersList = queryTaskParametersList(taskId, clubType, "asc");
                logger.warn("week=0      " + JSON.toJSONString(parametersList));
                Iterator<TbClubTaskParameter> it = parametersList.iterator();
                while (it.hasNext()) {
                    TbClubTaskParameter parameters = it.next();
                    if (weekFinishActivityCount >= parameters.getActivityTargetCount()
                            && weekFinishSignupCount >= parameters.getSignupTargetCount()) {
                        if (parametersList.size() > 1) {
                            it.remove();
                        }
                    }
                }
            }
            if (week == -1){
                parametersList = queryTaskParametersList(taskId, clubType, "desc");
                logger.warn("week=-1      " + JSON.toJSONString(parametersList));
                Iterator<TbClubTaskParameter> it = parametersList.iterator();
                while (it.hasNext()) {
                    TbClubTaskParameter parameters = it.next();
                    if (parameters.getActivityTargetCount() >  weekFinishActivityCount
                            || parameters.getSignupTargetCount() > weekFinishSignupCount) {
                        if (parametersList.size() > 1) {
                            it.remove();
                        }
                    }
                }
            }
        }
        TbClubTaskParameter showParameters = parametersList.get(0);
        logger.warn("本周任务参数：{}", JSON.toJSON(showParameters));

        EggTaskFinishCase weekTask = new EggTaskFinishCase();
        weekTask.setClubId(clubId);
        weekTask.setTaskParamterId(showParameters.getId());
        weekTask.setTaskId(clubTask.getId());
        if (week == 0){ //本周 0
//            if (weekFinishActivityCount >= maxLevel.getActivityTargetCount()
//                    && weekFinishSignupCount >= maxLevel.getSignupTargetCount()){
//                weekTask.setCanbeget(true);        //本周任务已经完成了最大级别，可以领取
//            }
            int finishLevel = getFinishLevel(taskId, clubType, weekFinishActivityCount, weekFinishSignupCount);
            weekTask.setFinishLevel(finishLevel);
            if (finishLevel != 0){      //如果有完成级别，获取完成的基本的参数id，在周任务统计的时候，用这个id记录到tb_club_task_summay_log
                weekTask.setTaskParamterId(getFinishLevelParameterId(taskId, clubType, weekFinishActivityCount, weekFinishSignupCount));
            }
        }else {         //上周 -1
            if ((weekFinishActivityCount != 0 && weekFinishActivityCount >= showParameters.getActivityTargetCount()) &&
                    (weekFinishSignupCount != 0 && weekFinishSignupCount >= showParameters.getSignupTargetCount())) {
                weekTask.setCanbeget(true);
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        String weekStr = clubTask.getTaskName() + "（" + sdf.format(weekMonday) + " - " + sdf.format(weekSunday) + "）";
        logger.warn("------------weekStr=" + weekStr);
        weekTask.setWeek(getWeekString(weekMonday));
        weekTask.setTaskName(weekStr);
        weekTask.setEgg(showParameters.getEggForClub());
        weekTask.setWeekActivityFinishCount(weekFinishActivityCount);
        weekTask.setWeekActivityTargetCount(showParameters.getActivityTargetCount());
        weekTask.setWeekSignupFinishCount(weekFinishSignupCount);
        weekTask.setWeekSignupPerson(getSignupPerson(thisWeekFishSignups));
        weekTask.setWeekSignupTargetCount(showParameters.getSignupTargetCount());
        weekTask.setWeekDate(weekMonday); //周一作为领取时间 //领取鸟蛋的时候，以周一作为此周的时间计算点

        TbClubTaskClubEggStreamExample eggStreamExample = new TbClubTaskClubEggStreamExample();
        eggStreamExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andWeekEqualTo(getWeekString(weekMonday));
        List<TbClubTaskClubEggStream> streams = clubTaskClubEggStreamMapper.selectByExample(eggStreamExample);       //此周任务是否已经领取
        if (streams != null && streams.size() > 0){     //已经领取任务，记录领取的鸟蛋
            weekTask.setAlreadyget(true);
            weekTask.setCanbeget(true);

            TbClubTaskClubEggStream stream = streams.get(0);
            weekTask.setEggForClub(stream.getEgg());
            weekTask.setEggForMem(stream.getEggForMem());
            weekTask.setGetAwardTime(stream.getCreateTime());       //奖励领取的时间
        }
        weekTask.setRule(getTaskRule(showParameters.getId()));
        weekTask.setRuleDesc(clubTask.getRuleDescLink());       //规则说明
        weekTask.setEggPerMem(showParameters.getEggForMem());
        weekTask.setMaxCount(showParameters.getMaxCountForMem());

        return weekTask;
    }

    private int getSignupPerson(List<ActivitySignUpInfo> thisWeekFishSignups){
        int weekSignupPerson = 0;
        Map<Integer, Integer> signupMap = new HashMap<>();
        for (ActivitySignUpInfo signUpInfo : thisWeekFishSignups){
            Integer orderUid = signUpInfo.getOrderUid();
            if (orderUid == null){
                continue;
            }
            if (!signupMap.containsKey(orderUid)){
                signupMap.put(orderUid, 1);
            }else {
                signupMap.put(orderUid, signupMap.get(orderUid)+1);
            }
        }
        return signupMap.size();
    }

    private int getFinishLevel(int taskId, int clubType, int weekActivityFinishCount, int weekSinupFinishCount){
        List<TbClubTaskParameter> parameterList = queryTaskParametersList(taskId, clubType, "desc");
        if (parameterList == null || parameterList.size() <= 1){
            return 0;
        }
        int finishLevel = -1;
        for (int i = 0; i < parameterList.size(); i++){
            if (parameterList.get(i).getActivityTargetCount() <= weekActivityFinishCount
                    && parameterList.get(i).getSignupTargetCount() <= weekSinupFinishCount){
                finishLevel = i;
                break;
            }
        }
        if (finishLevel == -1){
            return 0;
        }
        finishLevel = parameterList.size() - finishLevel;
        return finishLevel;
    }

    private int getFinishLevelParameterId(int taskId, int clubType, int weekActivityFinishCount, int weekSinupFinishCount){
        List<TbClubTaskParameter> parameterList = queryTaskParametersList(taskId, clubType, "desc");
        if (parameterList == null || parameterList.size() <= 1){
            return 0;
        }

        for (int i = 0; i < parameterList.size(); i++){
            if (parameterList.get(i).getActivityTargetCount() <= weekActivityFinishCount
                    && parameterList.get(i).getSignupTargetCount() <= weekSinupFinishCount){
               return parameterList.get(i).getId();
            }
        }
        return 0;
    }

    private String getTaskRule(int taskParameterId){

        TbClubTaskParameter parameter = clubTaskParameterMapper.selectByPrimaryKey(taskParameterId);
        if (parameter != null){
            return parameter.getRuleDesc();
        }
        return "";
    }

    private String getWeekString(Date date){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM.");
        return sf.format(date) + DateUtils.getWeekOfMonth(date);
    }

    /**
     * 计算周完成活动数（已结算活动）
     */
    private List<Integer> getWeekFinishActivityList(int clubId, Date startTime, Date endTime){      //一周内结算的活动
        startTime = DateUtils.dayBegin(startTime);
        endTime = DateUtils.dayEnd(endTime);
        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andDealMoneyGreaterThanOrEqualTo(new BigDecimal(1))
                .andCreateTimeGreaterThanOrEqualTo(startTime)
                .andCreateTimeLessThan(endTime);
        List<Integer> activitIds = new ArrayList<>();
        List<TbClubActivitySettlement> resultList = clubActivitySettlementMapper.selectByExample(example);
        if (resultList == null || resultList.size() == 0){
            return activitIds;
        }
        for (TbClubActivitySettlement settlement : resultList){
            if (!getActivityTimeInterval(settlement.getActivityId())){
                continue;
            }
            activitIds.add(settlement.getActivityId());
        }
        return activitIds;
    }

    /**
     * 活动时间大于一小时
     */
    private boolean getActivityTimeInterval(int activityId){
        TbActivity activity = activityMapper.selectByPrimaryKey(activityId);
        long t = activity.getEndTime().getTime() - activity.getStartTime().getTime();
        if (t/60*60*1000.0 >= 1){
            return true;
        }
        return false;
    }

    /**
     * 计算周报名人数（已结算活动）
     */
    private List<ActivitySignUpInfo> getWeekFinishSignupList(int clubId, BigDecimal minOrderAmount, List<Integer> activityIds){

        if (activityIds == null || activityIds.size()==0){
            return new ArrayList<>();
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("clubId", clubId);
        paramMap.put("minOrderAmount", minOrderAmount);
        paramMap.put("activityIds", activityIds);
        List<ActivitySignUpInfo> resultList = sqlSessionTemplate.selectList("selectClubActivitySignUpInfo", paramMap);
        if (resultList != null){
            return resultList;
        }
        return new ArrayList<>();
    }

    /**
     * 根据完成活动数，报名数，获取此类型俱乐部的最近达标参数
     */
//    private Integer getReachTargetPram(int clubType, int weekFinishActivityCount, int weekFinishSignupCount){
//
//        TbClubTaskExample
//                parametersExample = new TbClubTaskExample();
//        parametersExample.createCriteria()
//                .andClubTypeEqualTo(clubType);
//        parametersExample.setOrderByClause(" activity_target_count + signup_target_count desc"); //从大到小排序
//        List<TbClubTask> parametersList = clubTaskEggParametersMapper.selectByExample(parametersExample);
//        if (parametersList == null || parametersList.size() == 0){
//            throw new BizException("任务奖励活动还未开始！");
//        }
//        Iterator<TbClubTask> it = parametersList.iterator();
//        while (it.hasNext()) {
//            TbClubTask parameters = it.next();
//            if (parameters.getActivityTargetCount() >  weekFinishActivityCount &&       //如果目标数大于完成数移除
//                    parameters.getSignupTargetCount() > weekFinishSignupCount) {
//                it.remove();
//            }
//        }
//        if (parametersList.size() != 0) {
//            return parametersList.get(0).getId();
//        }
//        return  null;
//    }

    private Integer getClubTaskParameter(int clubType, int taskId, int finishActivityCount, int finishSignupCount){

        TbClubTaskParameterExample example = new TbClubTaskParameterExample();
        example.createCriteria()
                .andTaskIdEqualTo(taskId)
                .andClubTypeEqualTo(clubType);
        example.setOrderByClause(" activity_target_count + signup_target_count desc"); //从大到小排序
        List<TbClubTaskParameter> parameterList = clubTaskParameterMapper.selectByExample(example);
        if (parameterList == null || parameterList.size() == 0){
            throw new BizException("任务奖励活动还未开始！");
        }
        if (taskId == 1) {
            Iterator<TbClubTaskParameter> it = parameterList.iterator();
            while (it.hasNext()) {
                TbClubTaskParameter parameters = it.next();
                if (parameters.getActivityTargetCount() > finishActivityCount ||       //如果目标数大于完成数移除
                        parameters.getSignupTargetCount() > finishSignupCount) {
                    it.remove();
                }
            }
        }
        if (parameterList.size() != 0) {
            return parameterList.get(0).getId();
        }
        return  null;
    }

    /**
     * 领取俱乐部任务鸟蛋
     * @param clubId            俱乐部id
     */
    @Override
    @Transactional
    public Map<String, Object> giveOutEggs(int currentUid, int clubId, Date weekDate) {

        Map<Integer, Long> egg4User = new HashMap<>();

        //再次校验，是否可以发放鸟蛋
        Date thisWeekMonday = DateUtils.getMondayOfWeek(weekDate, 0);
        Date thisWeekSunday = DateUtils.getSundayOfWeek(weekDate, 0);

        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub.getUid() != currentUid){
            throw new BizException("只有俱乐部主席可以领取奖励！");
        }
        TbClubTask clubTask = getClubTask(tbClub.getClubType());
        Date now = new Date();
        if (clubTask == null || clubTask.getStatus() != 1){
            throw new BizException("当前类型的俱乐部没有奖励任务");
        }
        BigDecimal minPrice = getActivityMinPrice(tbClub.getClubType(), clubTask.getId());

        List<Integer> factivityIds = getWeekFinishActivityList(clubId, thisWeekMonday, thisWeekSunday);
        int finishActivityCount = factivityIds.size();
        List<ActivitySignUpInfo> activitySignUpInfoList = getWeekFinishSignupList(clubId, minPrice,    //订单金额大于=1元的才算数
                factivityIds);
        int finishSignupCount = activitySignUpInfoList.size();
        logger.warn("----------领取鸟蛋时：finishActivityCount=" + finishActivityCount + ", finishSignupCount=" + finishSignupCount);


        if (clubTask.getActiveTimeStart() != null && clubTask.getActiveTimeEnd() != null        //任务有效时间
                && !(now.after(clubTask.getActiveTimeStart()) && now.before(clubTask.getMultipleEndTime()))){
            throw new BizException("俱乐部奖励活动已经过期");
        }
        int taskId = clubTask.getId();

        //重新计算达到的任务级别，原因：如果页面停留很长一段时间，这段时间可能有用户退款、用户继续报名操作，需重新计算完成达到的任务级别
        Integer calculateTaskParamterId = getClubTaskParameter(tbClub.getClubType(), taskId, finishActivityCount, finishSignupCount);
        if (calculateTaskParamterId == null){
            throw new BizException("任务未达标，请重新刷新页面查看完成情况！");
        }

        TbClubTaskParameter parameters = clubTaskParameterMapper.selectByPrimaryKey(calculateTaskParamterId);
        logger.warn("----------计算到的taskParamterId=" + calculateTaskParamterId + ", " + JSON.toJSONString(parameters));
        Integer multiple = clubTask.getMultiple();    //倍数
        int eggForClub = parameters.getEggForClub();
        int eggForMem = parameters.getEggForMem();

        if (finishActivityCount < parameters.getActivityTargetCount()
                || finishSignupCount < parameters.getSignupTargetCount()){
            throw new BizException("任务未达标，不能领取鸟蛋！");
        }

        //再次校验，鸟蛋是否已经领取
        TbClubTaskClubEggStreamExample eggStreamExample = new TbClubTaskClubEggStreamExample();
        eggStreamExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andWeekEqualTo(getWeekString(weekDate));
        int count = clubTaskClubEggStreamMapper.countByExample(eggStreamExample);       //此周任务是否已经领取
        if (count > 0){
            throw new BizException("已经领取了此任务的鸟蛋！");
        }

//        DateTime curTime = DateTime.now();
//        Date start = DateUtils.dayBegin(curTime.withDayOfWeek(1).toDate());
//        Date end = DateUtils.dayEnd(curTime.withDayOfWeek(7).toDate());
//
//        //再次校验，鸟蛋是否已经领取
//        TbClubTaskClubEggStreamExample eggStreamExample = new TbClubTaskClubEggStreamExample();
//        eggStreamExample.createCriteria()
//                .andClubIdEqualTo(clubId)
//                .andCreateTimeGreaterThanOrEqualTo(start)
//                .andCreateTimeLessThanOrEqualTo(end);
//        int count = clubTaskClubEggStreamMapper.countByExample(eggStreamExample);       //此周任务是否已经领取
//        if (count > 0) {
//            throw new BizException("已经领取了此任务的鸟蛋！");
//        }

        //判断是否发放倍数奖励
        boolean isMultiple = false;
        if (multiple != null){
            if (clubTask.getMultipleStartTime() != null && now.after(clubTask.getMultipleStartTime())
                    && clubTask.getMultipleEndTime() != null && now.before(clubTask.getMultipleEndTime())){
                isMultiple = true;
            }
        }

        Integer clubPresidentUid = tbClub.getUid();
        //计算发放给俱乐部主席的鸟蛋
        if (isMultiple){
            eggForClub = eggForClub*multiple;
        }

        //计算各参加活动的成员需要发放多少个鸟蛋
        Map<Integer, List<Integer>> uid2ActivityIdMap = new HashMap<>();
        for (ActivitySignUpInfo signUpInfo : activitySignUpInfoList){
            Integer uid = signUpInfo.getOrderUid();
            if (uid == null){       //排除代报名的人
                continue;
            }
            if (!uid2ActivityIdMap.containsKey(uid)){
                List<Integer> activityIds = new ArrayList<>();
                activityIds.add(signUpInfo.getActivityId());
                uid2ActivityIdMap.put(uid, activityIds);
            }else {
                List<Integer> activityIds = uid2ActivityIdMap.get(uid);
                activityIds.add(signUpInfo.getActivityId());
                uid2ActivityIdMap.put(uid, activityIds);
            }
        }
        Set<Integer> keySet = uid2ActivityIdMap.keySet();
        int totalEggForMem = 0;     //发放给成员的鸟蛋总数
        for (Integer uid : keySet){
            int signUpCount = uid2ActivityIdMap.get(uid).size();
            //需要发放给此用户的鸟蛋个数
            if (signUpCount >= parameters.getMaxCountForMem()){
                signUpCount = parameters.getMaxCountForMem();     //每周最多领取鸟蛋的次数
            }
            int egg = eggForMem*signUpCount;
            if (isMultiple){        //如果发放倍数
                egg = egg*multiple;
            }
            if (!isClubMember(clubId, uid)){        //不是俱乐部成员不给发鸟蛋
                continue;
            }
            egg4User.put(uid, (long)egg);
            totalEggForMem += egg;
        }

        //判断是否可以发放鸟蛋，总鸟蛋数是否够
        Integer costEgg = clubEggTaskMapper.calculateAlreadyGiveOutEggsOfClub(calculateTaskParamterId);
        costEgg = costEgg==null?0:costEgg;
        int leftEggs = clubTask.getTotalEgg() - costEgg;
        logger.warn("准备给主席{}发：{}, 成员发：{}，任务{}还剩{}", tbClub.getUid(), eggForClub, totalEggForMem, taskId, leftEggs);

        if (clubTask.getTotalEgg() !=-1     //-1 代表不限制
                && leftEggs < (eggForClub + totalEggForMem)){
            clubTask.setStatus(3);    //鸟蛋已经领完
            clubTaskMapper.updateByPrimaryKeySelective(clubTask);
            throw new BizException("鸟蛋已经领完了，下次再来吧");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd");
        String taskName = "(" + clubTask.getTaskName() + sdf.format(DateUtils.getMondayOfWeek(weekDate, 0)) + " - " + sdf.format(DateUtils.getSundayOfWeek(weekDate, 0)) + ")";
        //记录成员领取鸟蛋流水
        for (Integer uid : keySet){
            if (!isClubMember(clubId, uid)){
                continue;
            }
            TbClubTaskMemEggStream memEggStream = new TbClubTaskMemEggStream();
            memEggStream.setClubId(clubId);
            memEggStream.setMemberUid(uid);
            memEggStream.setTaskId(taskId);
            memEggStream.setEgg(egg4User.get(uid).intValue());
            memEggStream.setWeek(getWeekString(weekDate));
            memEggStream.setActivityIds(JSON.toJSONString(uid2ActivityIdMap.get(uid)));
            clubTaskMemEggStreamMapper.insertSelective(memEggStream);

            cppService.pushClubCommonMsg(tbClub.getLogoUrl(), "恭喜您获得俱乐部\""+tbClub.getClubName()+"\"的" + taskName + "奖励" + egg4User.get(uid).intValue() + "鸟蛋！", Arrays.asList(uid));
        }

        //记录鸟蛋已领取
        EggTaskFinishCase taskFinishCase = new EggTaskFinishCase();
        taskFinishCase.setWeek(getWeekString(weekDate));
        taskFinishCase.setWeekDate(weekDate);
        taskFinishCase.setClubId(clubId);
        taskFinishCase.setCanbeget(true);
        taskFinishCase.setAlreadyget(true);
        taskFinishCase.setTaskId(taskId);
        taskFinishCase.setTaskParamterId(parameters.getId());
        taskFinishCase.setWeekActivityTargetCount(parameters.getActivityTargetCount());
        taskFinishCase.setWeekActivityFinishCount(finishActivityCount);
        taskFinishCase.setWeekSignupTargetCount(parameters.getSignupTargetCount());
        taskFinishCase.setWeekSignupFinishCount(finishSignupCount);
        taskFinishCase.setEggForClub(eggForClub);
        taskFinishCase.setEggForMem(totalEggForMem);
        taskFinishCase.setGetAwardTime(new Date());
        taskFinishCase.setWeekSignupPerson(getSignupPerson(activitySignUpInfoList));

        recordClubWeekTaskSummary(taskFinishCase, false);

        //发放鸟蛋给俱乐部主席
        APIRequest<ReqUserAccumulateModify> api = giveoutEgg4ClubPresident(clubPresidentUid, (long)eggForClub, (long)totalEggForMem,
                clubId, parameters.getId(), weekDate, factivityIds, activitySignUpInfoList);

        //发放鸟蛋给参加此俱乐部活动的用户
        logger.warn("发放俱乐部任务鸟蛋：{}", JSON.toJSON(egg4User));
        APIRequest<List<ReqUserAccumulateModify>> apiList = batchGiveoutEgg4Mem(egg4User);

        if(null != api)
        {
            APIResponse<RespUserAccumulateModify> response =  userAssetsService.modifyAccumulate(api);
            if (!response.isRet()){
                throw new BizException("发放鸟蛋给俱乐部主席失败，"+response.getErrmsg());
            }
        }

        if(null != apiList){
            APIResponse apiResponse = userAssetsService.batchModifyEgg(apiList);
            if (!apiResponse.isRet()){
                throw new BizException("发放俱乐部成员鸟蛋失败！");
            }
        }
        //推送消息给俱乐部主席
        cppService.pushClubCommonMsg(tbClub.getLogoUrl(), "恭喜您获得\"" + taskName + "\"的" + "奖励" + eggForClub + "鸟蛋！", Arrays.asList(tbClub.getUid()));

        Map<String, Object> map = new HashMap<>();
        map.put("eggForClub", eggForClub);
        map.put("eggForMem", totalEggForMem);
        return map;
    }

    @Override
    public void recordClubWeekTaskSummary(EggTaskFinishCase taskFinishCase, boolean summary){

        TbClubTaskSummaryLog log = new TbClubTaskSummaryLog();
        log.setWeek(taskFinishCase.getWeek());
        log.setClubId(taskFinishCase.getClubId());
        log.setTaskId(taskFinishCase.getTaskId());
        log.setIsFinishTask(taskFinishCase.isCanbeget());
        boolean isGotAwards = taskFinishCase.isAlreadyget();
        log.setIsGotAwards(isGotAwards);
        log.setTaskParameterId(taskFinishCase.getTaskParamterId());

        int f_activity_count = taskFinishCase.getWeekActivityFinishCount();
        int f_signup_count = taskFinishCase.getWeekSignupFinishCount();
        log.setActivityCount(f_activity_count);
        log.setSignupCount(f_signup_count);
        log.setSignupPerson(taskFinishCase.getWeekSignupPerson());

        if (isGotAwards){
            log.setClubGetEggs(taskFinishCase.getEggForClub());
            log.setMemGetEggs(taskFinishCase.getEggForMem());
            log.setCoefficient(getCoefficient(taskFinishCase));
            log.setGetAwardsTime(taskFinishCase.getGetAwardTime());
            log.setCreateTime(taskFinishCase.getWeekDate());
            log.setUpdateTime(taskFinishCase.getWeekDate());
        }else {
            log.setCreateTime(new Date());
            log.setUpdateTime(new Date());
        }

        TbClubTaskSummaryLogExample example = new TbClubTaskSummaryLogExample();
        example.createCriteria()
                .andTaskIdEqualTo(taskFinishCase.getTaskId())
                .andClubIdEqualTo(taskFinishCase.getClubId())
                .andWeekEqualTo(taskFinishCase.getWeek());

        if (clubTaskSummaryLogMapper.countByExample(example) == 0){     //本周已经统计了不再统计
            clubTaskSummaryLogMapper.insertSelective(log);
            logger.warn("--------------------------------------------记录 task log: " + JSON.toJSONString(log));
        }else {
            clubTaskSummaryLogMapper.updateByExampleSelective(log, example);
            logger.warn("--------------------------------------------更新 task log: " + JSON.toJSONString(log));
        }

        //只有周日才更新积分统计结果
        if (summary && (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)){
            clubIntegralService.modifyClubWeekTaskStar(taskFinishCase.getClubId(),
                taskFinishCase.getWeekActivityFinishCount(), taskFinishCase.getWeekActivityTargetCount(),
                taskFinishCase.getWeekSignupFinishCount(), taskFinishCase.getWeekSignupTargetCount());
            clubIntegralService.calcClubActivityMember(taskFinishCase.getClubId(), taskFinishCase.getWeekSignupPerson());
        }
    }

    @Override
    public double getCoefficient(EggTaskFinishCase taskFinishCase){
        int f_activity_count = taskFinishCase.getWeekActivityFinishCount();     //实际完成
        int f_signup_count = taskFinishCase.getWeekSignupFinishCount();
        int t_activity_count = taskFinishCase.getWeekActivityTargetCount();     //实际
        int t_signup_count = taskFinishCase.getWeekSignupTargetCount();

        double coefficient = 0d;
        if (f_activity_count > t_activity_count && f_signup_count > t_signup_count){      //  	超额完成公式：{实际活动数/任务要求活动数+(（实际完成人次数-任务要求人次数)/任务要求人次数）* 0.7 + 1}/2；
            coefficient = (f_activity_count/(t_activity_count*1.0) + (((f_signup_count-t_signup_count)/(t_signup_count*1.0))/(t_signup_count*1.0))*0.7 +1)/2.0;
        }else {             //  	未完成任务公式：（实际完成活动数/任务要求活动数+实际完成人次数/任务要求人次数）/2
            coefficient = (f_activity_count/t_activity_count + f_signup_count/t_signup_count)/2.0;
        }

        return coefficient;
    }

    private boolean isClubMember(int clubId, int uid){
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId).andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return clubMemberMapper.countByExample(example)>0;
    }

    /**
     *  发送鸟蛋给俱乐部主席
     */
    private APIRequest<ReqUserAccumulateModify> giveoutEgg4ClubPresident(Integer uid, Long eggs, Long eggsForMem, int clubId, int taskId, Date weekDate,
                                          List<Integer> factivityIds, List<ActivitySignUpInfo> activitySignUpInfoList){
        ReqUserAccumulateModify modify = new ReqUserAccumulateModify();
        modify.setUid(uid);
        modify.setAccumulate(eggs);
        modify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
        modify.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        modify.setBusinessCode(ClubConstants.CLUB_EGG_WEEK_TASK_CODE);
        RespUserInfoBase userInfo = getUserInfoBase(uid);
        String userName = "";
        if (userInfo != null) {
            userName = userInfo.getNickName();
            modify.setReceiver(userInfo.getNickName());
        }
        modify.setPayReceive("系统发放");
        modify.setInfo("任务奖励");

        APIRequest<ReqUserAccumulateModify> apiRequest = new APIRequest<>();
        apiRequest.setData(modify);

        //记录俱乐部领取鸟蛋的流水
        TbClubTaskClubEggStream clubEggStream = new TbClubTaskClubEggStream();
        clubEggStream.setClubId(clubId);
        clubEggStream.setTaskId(taskId);
        clubEggStream.setEgg(eggs.intValue());
        clubEggStream.setEggForMem(eggsForMem.intValue());
        clubEggStream.setWeek(getWeekString(weekDate));
        clubEggStream.setUid(uid);
        clubEggStream.setActivityIds(JSON.toJSONString(factivityIds));
        clubEggStream.setSignupInfo(JSON.toJSONString(activitySignUpInfoList));
        clubTaskClubEggStreamMapper.insertSelective(clubEggStream);
        return apiRequest;
    }

    /**
     * 发送mq通知资产系统，批量更新用户的鸟蛋
     */
    private APIRequest<List<ReqUserAccumulateModify>> batchGiveoutEgg4Mem(Map<Integer, Long> egg4User){

//        MqRequestMsg mqRequestMsg = new MqRequestMsg();
//        mqRequestMsg.setMsgId(UUID.randomUUID().toString());
//        mqRequestMsg.setTopic(MqConstant.ASSETS_BATCH_ADD_EGG_CLUB);
//        mqRequestMsg.setFlag(0);
//        mqRequestMsg.setTag( Constants.ASSETS_SYSTEM_CODE);
//        mqRequestMsg.setBody(ObjectUtil.toByteArray(egg4User));
//        batchGiveOutEggsProducer.syncSend(mqRequestMsg);

        if (egg4User.isEmpty()){
            return null;
        }
        Map<Integer, RespUserInfoBase> respUserInfoBases = new HashMap<>();
        List<Integer> uids = new ArrayList<>(egg4User.keySet());
        int length = uids.size();
        int pageSize = 10;
        int page = length/pageSize;
        for (int i = 0; i < page; i++) {
            Map<Integer, RespUserInfoBase> userMaps = userServiceFacade.batchQueryUserInfoToMap(uids.subList(i*pageSize, (i+1)*pageSize));
            respUserInfoBases.putAll(userMaps);
            if(MapUtils.isNotEmpty(userMaps))
            {
                respUserInfoBases.putAll(userMaps);
            }
        }
        //有不足一页的
        int last = length%pageSize;
        if(last > 0)
        {
            Map<Integer, RespUserInfoBase> usersMaps = userServiceFacade.batchQueryUserInfoToMap(uids.subList(page*pageSize, length));
            if(MapUtils.isNotEmpty(usersMaps))
            {
                respUserInfoBases.putAll(usersMaps);
            }
        }

        List<ReqUserAccumulateModify> reqUserAccumulateModifies = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : egg4User.entrySet()) {
            ReqUserAccumulateModify modify = new ReqUserAccumulateModify();
            modify.setUid(entry.getKey());
            modify.setAccumulate(entry.getValue());
            modify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
            modify.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            modify.setBusinessCode(ClubConstants.CLUB_EGG_WEEK_TASK_CODE);
            RespUserInfoBase userInfo = respUserInfoBases.get(entry.getKey());
            if (userInfo != null) {
                modify.setReceiver(userInfo.getNickName());
            }
            modify.setPayReceive(AssetsPayReceive.SYSTEM.getName());
            modify.setInfo("任务奖励");
            reqUserAccumulateModifies.add(modify);
        }
        APIRequest<List<ReqUserAccumulateModify>> apiRequest=new APIRequest<>();
        apiRequest.setData(reqUserAccumulateModifies);
        return apiRequest;
    }

    /**
     * 任务列表
     * @param clubId        俱乐部id
     * @param pageNo        页码
     * @param pageSize      每页记录数
     * @return
     */
    @Override
    public PageObj<List<TaskInfo>> getClubTaskInfoList(int clubId, int pageNo, int pageSize){

        Date sundayEnd = DateUtils.dayBegin(DateUtils.getMondayOfWeek(new Date(), 0));
        Integer total = clubEggTaskMapper.countClubTaskList(clubId, sundayEnd);
        total = total==null?0:total;
        Limit limit = Limit.buildLimit(pageNo+1, pageSize);
        List<TaskInfo> taskInfoList = clubEggTaskMapper.selectClubTaskList(clubId, sundayEnd, limit.getStart(), pageSize);
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        if (taskInfoList != null && taskInfoList.size() != 0){
            for (TaskInfo taskInfo : taskInfoList){
                int taskId = taskInfo.getTaskId();
                if (taskId == 1) {
                    taskInfo.setTaskType(1);
                    Date weekDate = taskInfo.getWeekDate();
                    if (weekDate.before(DateUtils.getMondayOfWeek(new Date(), 0))) {
                        boolean canbeget = judgeLastWeekCanbeget(taskInfo.getFinishActivityCount(), taskInfo.getFinishSignupCount(),
                                taskInfo.getTaskParameterId(), weekDate);
                        taskInfo.setCanbeget(canbeget);
                    }

                    taskInfo.setTaskName(taskInfo.getTaskName() + "（" + sdf.format(DateUtils.getMondayOfWeek(weekDate, 0)) + " - " + sdf.format(DateUtils.getSundayOfWeek(weekDate, 0)) + "）");
                    taskInfo.setWeekDate((DateUtils.getMondayOfWeek(weekDate, 0))); //领取鸟蛋的时候，以周一作为此周的时间计算点
                    taskInfo.setWeek(getWeekString(taskInfo.getWeekDate()));
                    taskInfo.setTaskRule(getTaskRule(taskInfo.getTaskParameterId()));
                    int status = taskInfo.getTaskStatus();
                    if (status != 1 && taskInfo.isCanbeget() && !taskInfo.isAlreadyget()) {    //任务暂停并且鸟蛋没有领取，在这里不能领取鸟蛋
                        taskInfo.setCanbeget(false);
                    }
                    if (taskInfo.isAlreadyget()) {
                        List<MemberGotEggInfo> memberGotEggInfoList = getMemberGotEggInfoList(clubId, taskInfo.getTaskId(), taskInfo.getWeek());
                        taskInfo.setMemberGotEggInfoList(memberGotEggInfoList);
                    }
                }
                if (taskId == 2){
                    taskInfo.setTaskType(2);
                    taskInfo.setTaskRule(getTaskRule(taskInfo.getTaskParameterId()));
                    taskInfo.setMemberGotEggInfoList(getMemberGotEggInfoList(clubId, taskInfo.getTaskId(), taskInfo.getWeek()));
                }
            }
        }

        return  PageObj.create(total, pageNo, pageSize, taskInfoList);
    }

    private boolean judgeLastWeekCanbeget(int weekFinishActivityCount, int weekFinishSignupCount, int taskLevelParameterId, Date weekDate){

        TbClubTaskParameter showParameters = clubTaskParameterMapper.selectByPrimaryKey(taskLevelParameterId);
        if (showParameters == null){
            return false;
        }
        if ((weekFinishActivityCount != 0 && weekFinishActivityCount >= showParameters.getActivityTargetCount()) &&
                (weekFinishSignupCount != 0 && weekFinishSignupCount >= showParameters.getSignupTargetCount())) {
            return true;
        }
        return false;
    }

    private List<MemberGotEggInfo> getMemberGotEggInfoList(int clubId, int taskId, String week){

        List<MemberGotEggInfo> memberGotEggInfoList = new ArrayList<>();

        TbClubTaskMemEggStreamExample eggStreamExample = new TbClubTaskMemEggStreamExample();
        TbClubTaskMemEggStreamExample.Criteria criteria = eggStreamExample.createCriteria();
                criteria.andClubIdEqualTo(clubId)
                .andTaskIdEqualTo(taskId);
        if (taskId == 1) {
            criteria.andWeekEqualTo(week);
        }

        List<TbClubTaskMemEggStream> streams = clubTaskMemEggStreamMapper.selectByExample(eggStreamExample);
        List<Integer> uids = new ArrayList<>();
        if (streams != null && streams.size() != 0){
            for (TbClubTaskMemEggStream stream :streams){
                int uid = stream.getMemberUid();
                uids.add(uid);
            }

            Map<Integer, RespUserInfoBase> map = userServiceFacade.batchQueryUserInfoToMap(uids);
            for (TbClubTaskMemEggStream stream :streams) {
                MemberGotEggInfo eggInfo = new MemberGotEggInfo();
                eggInfo.setEggs(stream.getEgg());
                RespUserInfoBase userInfo = map.get(stream.getMemberUid());
                if (userInfo != null) {
                    eggInfo.setAvatar(userInfo.getIcon());
                    eggInfo.setUserName(userInfo.getNickName());
                }
                memberGotEggInfoList.add(eggInfo);
            }
        }

        return memberGotEggInfoList;
    }

    /**
     * 查询俱乐部一周内结算的活动列表
     * @param clubId        俱乐部id
     * @param weekDate      一周中任何一天
     * @return
     */
    @Override
    public List<TaskActivityInfo> getTaskActivityInfoOfThisWeek(int clubId, Date weekDate){

        Date startTime = DateUtils.getMondayOfWeek(weekDate, 0);
        Date endTime = DateUtils.getSundayOfWeek(weekDate, 0);
        List<TaskActivityInfo> activityInfos = clubEggTaskMapper.selectClubTaskActivityList(clubId,
                DateUtils.dayBegin(startTime), DateUtils.dayEnd(endTime));
        if (activityInfos != null && activityInfos.size() != 0){
            for (TaskActivityInfo taskActivityInfo : activityInfos){
                if (taskActivityInfo.getActivityAddress() == null && taskActivityInfo.getPlaceId() != 0){
                    //活动地址为所在场馆地址
                    int placeId = taskActivityInfo.getPlaceId();
                    Map<Integer, PlaceDubboProvider> providerMap = placeClient.getPlaceBySinglePlaceId(placeId);
                    if (providerMap != null && !providerMap.isEmpty()){
                        taskActivityInfo.setActivityAddress(providerMap.get(placeId).getAddress());
                    }
                }
                taskActivityInfo.setSignupCount(clubEggTaskMapper.calculateSignupCount(clubId, taskActivityInfo.getActivityId()));
            }
        }
        return activityInfos;
    }

}
